package self.hoy.demo.cloud.nacos.test;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.junit.Test;

import java.util.Properties;

/**
 * @author 三共小不
 * @date 2021/7/1
 */
public class ServiceConsumer {
    private static final String SERVICE_NAME = "nacos-payment-provider";
    @Test
    public void testSubscribe() throws NacosException {
        Properties properties = new Properties();
        properties.setProperty("serverAddr", "nacos-host:8849");
//        properties.setProperty("namespace", "6aafcc1e-9ef2-4990-9036-bc2e2b3adbee");
        NamingService namingService = NamingFactory.createNamingService(properties);
        namingService.subscribe(SERVICE_NAME, event -> {
            NamingEvent namingEvent = (NamingEvent) event;
            printInstances(namingEvent);
            mockConsume(namingService, SERVICE_NAME);
        });
    }

    private void printInstances(NamingEvent namingEvent) {
        System.out.println(namingEvent);
    }

    private void mockConsume(NamingService namingService, String serviceName) {
        int i = 0, loop = 5;
        try {
            while (i++ < loop) {
                Instance instance = namingService.selectOneHealthyInstance(serviceName);
                if (instance != null) {
                    System.out.println(instance);
                }
            }
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
}
